package com.xgq.drink.controller;

import com.xgq.drink.entity.Product;
import com.xgq.drink.entity.R;
import com.xgq.drink.entity.dto.ProductVO;
import com.xgq.drink.mapper.ProductMapper;
import com.xgq.drink.service.ICategoryService;
import com.xgq.drink.service.IProductService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xgq.drink.utils.JwtTokenUtil;
import com.xgq.drink.utils.RUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/product")
@Tag(name = "产品模块", description = "产品查询接口")
public class ProductController {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private IProductService productService;
    @Autowired
    private ProductMapper productMapper;

    // 分页查询商品
    @GetMapping("/list")
    public IPage<Product> getProductList(@RequestParam(defaultValue = "1") int current,
                                         @RequestParam(defaultValue = "10") int size) {
        Page<Product> page = new Page<>(current, size);
        return productService.getProductList(page);
    }
    @DeleteMapping("/{productId}")
    @Operation(summary = "逻辑删除商品")
    public R logicDeleteProduct(
            @PathVariable Long productId,
            HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long brandId = jwtTokenUtil.getStoreIdFromToken(token);

        int result = productService.logicDeleteProduct(productId, brandId);
        return result > 0 ?
                RUtils.success("删除成功") :
                RUtils.fail("删除失败或无权限");
    }
    @PostMapping("/open/{productId}")
    @Operation(summary = "启用")
    public R logicDeleteProduct2(
            @PathVariable Long productId,
            HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long brandId = jwtTokenUtil.getStoreIdFromToken(token);

        int result = productMapper.openLogicDeleteById(productId,brandId);
        return result > 0 ?
                RUtils.success("删除成功") :
                RUtils.fail("删除失败或无权限");
    }
    // 增强版商品列表查询（支持多条件）
    @GetMapping("/list/condition")
    public IPage<Product> getProductListWithConditions(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice,
            @RequestParam(required = false) Long categoryId) {
        Page<Product> page = new Page<>(current, size);
        return productService.getProductListWithConditions(page, productName, minPrice, maxPrice, categoryId);
    }
    // 增强版品牌商品查询（支持多条件）
    @GetMapping("/list/brand/condition")
    public IPage<Product> getBrandProductsWithConditions(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Long productId,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice,
            @RequestParam(required = false) LocalDateTime updateTime) {
        String token = request.getHeader("Authorization");
        Long brandId = jwtTokenUtil.getStoreIdFromToken(token);
        Page<Product> page = new Page<>(current, size);
        return productService.getBrandProductsWithConditions(page, brandId, productName, productId,
                categoryId, minPrice, maxPrice, updateTime);
    }
    @GetMapping("/list/brand/conditionByUser")
    public IPage<Product> getBrandProductsWithConditionsByUser(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Long productId,
            @RequestParam(required = false) Long brandId,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice,
            @RequestParam(required = false) LocalDateTime updateTime) {
        Page<Product> page = new Page<>(current, size);
        return productService.getBrandProductsWithConditions(page, brandId, productName, productId,
                categoryId, minPrice, maxPrice, updateTime);
    }
    @GetMapping("/list/category/{categoryId}")
    public IPage<Product> getProductListByCategory(@RequestParam(defaultValue = "1") int current,
                                                   @RequestParam(defaultValue = "10") int size,
                                                   @PathVariable Long categoryId) {
        Page<Product> page = new Page<>(current, size);
        return productService.getProductListByCategory(page, categoryId);
    }
    //品牌查询
    @GetMapping("/list/brand")
    public IPage<Product> getProductListByBrandId(@RequestParam(defaultValue = "1") int current,
                                                  @RequestParam(defaultValue = "10") int size, HttpServletRequest request) {
        System.out.println("/list/brand");
        String token = request.getHeader("Authorization");
        Long brandId =jwtTokenUtil.getStoreIdFromToken(token);
        Page<Product> page = new Page<>(current, size);
        return productService.getProductListByBrandId(page, brandId);
    }
    // 根据商品 ID 查询商品详情
    @GetMapping("/{productId}")
    public Product getProductDetailById(@PathVariable Long productId) {
        return productService.getProductDetailById(productId);
    }
    // 推荐商品
    @GetMapping("/recommend")
    public IPage<Product> getRecommendations(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request
    ) {
        String token = request.getHeader("Authorization");
        Long userId = Long.valueOf(jwtTokenUtil.getUserIdFromToken(token)); // 需要实现用户ID获取
        Page<Product> page = new Page<>(current, size);
        return productService.getRecommendations(page, userId);
    }

    // 新增商品
    @PostMapping("/add")
    @Operation(summary = "新增商品")
    public R addProductWithAttributes(@RequestBody Product product,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long brandId = jwtTokenUtil.getStoreIdFromToken(token);
        product.setBrandId(brandId);
        if (productService.saveProductWithAttributes(product)){
            return RUtils.success("商品添加成功");
        }else {
            return RUtils.fail("商品添加失败");
        }
    }
    // 修改商品
    @PutMapping("/credit")
    @Operation(summary = "修改商品信息")
    public R updateProduct(@RequestBody Product product, HttpServletRequest request) {
        if (productService.updateProduct(product)!=0)
            return RUtils.success("商品修改成功");
        // 如果尝试了三次仍然失败，返回失败信息
        return RUtils.fail("商品修改失败");
    }
    @Autowired
    private ICategoryService categoryService;
    @GetMapping("/list/categoryTree/{categoryId}")
    @Operation(summary = "分类树商品查询")
    public IPage<Product> getProductListByCategoryTree(
            @PathVariable Long categoryId,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        Page<Product> page = new Page<>(current, size);
        return productService.getProductsByCategoryTree(page, categoryId);
    }

    /**
     * 商品访问量统计
     * @param startTime 开始时间(yyyy-MM-dd HH:mm:ss)
     * @param endTime 结束时间(yyyy-MM-dd HH:mm:ss)
     */
    @GetMapping("/stats/views")
    @Operation(summary = "商品访问量统计")
    public R getViewStats(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        Map<String, Object> result = productService.getProductViewStats(startTime, endTime);
        return RUtils.success("OK",result);
    }

    /**
     * 商品订单量统计
     * @param startTime 开始时间(yyyy-MM-dd HH:mm:ss)
     * @param endTime 结束时间(yyyy-MM-dd HH:mm:ss)
     */
    @GetMapping("/stats/orders")
    @Operation(summary = "商品订单量统计")
    public R getOrderStats(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        Map<String, Object> result = productService.getProductOrderStats(startTime, endTime);
        return RUtils.success("OK",result);
    }

    /**
     * 商品支付金额统计
     * @param startTime 开始时间(yyyy-MM-dd HH:mm:ss)
     * @param endTime 结束时间(yyyy-MM-dd HH:mm:ss)
     */
    @GetMapping("/stats/payments")
    @Operation(summary = "商品支付金额统计")
    public R getPaymentStats(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        Map<String, Object> result = productService.getProductPaymentStats(startTime, endTime);
        return RUtils.success("OK",result);
    }

}